%% Author: Administrator
%% Created: 2009-2-26
%% Description: TODO: Add description to data_importer
-module(data_importer).

%%
%% Include files
%%
-include("map.hrl").

-include("data_util.hrl").

-define(SERVER, e2d_server).
-define(ZoomLevel, 15).


%%
%% Exported Functions
%%
-export([scan/1]).
-export([get_files_dir/1]).

%%
%% API Functions
%%
scan(Level) ->
    ListFile = get_files_dir(Level) ++ "list.txt",
    io:format("list file: ~s~n", [ListFile]),
    {ok, IoDevice} = file:open(ListFile, read),
    _HeadLine = io:get_line(IoDevice, ''),
    each_line(IoDevice, io:get_line(IoDevice, ''), Level),
    file:close(IoDevice).

    
%%
%% Local Functions
%%
get_files_dir(Level) ->
    ?ROOT ++ integer_to_list(Level) ++ "/".

each_line(_IoDevice, eof, _Level) ->
    ok;
each_line(IoDevice, Line, Level) ->
    [FileName | Rest] = string:tokens(Line, ": \n"),
    [Left, Right, Top, Bottom] = 
        lists:map(fun(Str) -> 
                      {Float, []} = string:to_float(Str), 
                      Float 
                  end, Rest),
    Longitude = (Left + Right) / 2,
    Latitude = (Top + Bottom) / 2,
    CellId = geo_util:get_quadtree_address(Longitude, Latitude, Level),
%    spawn(fun() -> 
                  store_cell(CellId, FileName, Level) 
%          end)
    ,
    each_line(IoDevice, io:get_line(IoDevice, ''), Level).

store_cell(Id, FileName, Level) ->
    {ok, IoDevice} = file:open(get_files_dir(Level) ++ FileName, [raw, binary]),
    {ok, Data} = file:read(IoDevice, 30000),
    file:close(IoDevice),
    RT = #raster_tile{type="image/jpeg", data=Data},
    <<Key:128>> = crypto:md5(Id),
    CellValue = #cell{
                      id = Id, 
                      scale_factor = Level,
                      zone = geo_util:get_coordinates_from_address(Id), 
                      r_layer = RT
                },
    put(Key, undefined, CellValue).

put(Key, Context, Value) ->
%    gen_server:call(?SERVER, {api, {put, Key, Context, Value}}, infinity).
    ring_accessor:put_to_ring(Key, Value).

